# -*- encoding: utf-8 -*-

module Faye
  class Cors
    def incoming(message, request, callback)
      message['error'] = '403::Forbidden origin' unless valid?(request)
      callback.call(message)
    end

    private

    def valid?(request)
      source = request.env['HTTP_ORIGIN'] || request.env['HTTP_X_ORIGIN'] || request.env['HTTP_REFERER']
      source.nil? || include?(source)
    end

    def include?(source)
      ['b2b2c', '121.40.', '10.171.', '192.168.', '127.0.0.1', 'localhost', '0.0.0.0'].any?{ |word| source.include?(word) }
    end
  end
end